<template>
  <div v-loading="loading">
    <div style="width:100%;height: 30px;text-align:right;"
         v-if="$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
      <el-button-group>
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   v-if="editMode"
                   size="small"
                   v-on:click.native='selectedgadgetPop'></el-button>
        <el-button type="primary"
                   plain
                   icon="el-icon-edit"
                   ref="toggleBtn"
                   size="small"
                   v-on:click.native='toggleClick'></el-button>
      </el-button-group>
    </div>
    <grid-layout :layout.sync="gadgets"
                 :col-num="12"
                 :row-height="10"
                 :is-draggable="dashbordDefaultSetting.allowDragging"
                 :is-resizable="dashbordDefaultSetting.allowResizing"
                 :vertical-compact="true"
                 :use-css-transforms="true">
      <grid-item v-for="(item,index) in gadgets"
                 :x="item.x"
                 :y="item.y"
                 :w="item.w"
                 :h="item.h"
                 :i="item.i"
                 :key="item.i"
                 @container-resized="containerResizedEvent"
                 @resized="resizedEvent"
                 @mouseenter.native="mouseEnterModule(index)"
                 @mouseleave.native="mouseLeaveModule(index)">
        <div v-if="editMode&&item&&item.showSetting&&item.showSetting === 'show'"
             style="height:20px;lineHeight:20px;position:absolute;top:-20px;right:0;z-index:2020;background:#ffffff;">
          &nbsp;
          <i @mouseenter="moveComponent(true)"
             @mouseleave="moveComponent(false)"
             :title="$t('custom.move')"
             class="el-icon-rank"
             style="cursor:pointer;"></i>&nbsp;
          <i v-if="$hasPermission('sys:tenant:model:allowtomanagesystemmodel')"
             @click="editComponent(item.i)"
             :title="$t('custom.edit')"
             class="el-icon-s-operation"
             style="cursor:pointer;"></i>&nbsp;
          <i @click="closeComponent(item.i)"
             :title="$t('custom.remove')"
             class="el-icon-close"
             style="cursor:pointer;"></i>&nbsp;
        </div>
        <component :editMode='editMode'
                   :gadgetInfo='item'
                   @dragChanged='gadgetDragChanged'
                   ref="gadgets"
                   @removed='gadgetRemoved'
                   :id='item.i'
                   :pageId='pageId'
                   :is="item.com"></component>
      </grid-item>
    </grid-layout>
    <el-dialog :title="$t('custom.dashboard.layoutSelectionTitle')"
               :visible.sync="dialog"
               :modal='false'
               width="50%">
      <el-container>
        <el-tabs tab-position="left"
                 style="width: 100%;height:50vh;overflow-y: auto;">
          <el-tab-pane :label="$t('custom.dashboard.layoutStandard')">
            <el-row>
              <el-col :span="6"
                      class="layout-item"
                      v-for="layoutItem in layoutItems"
                      :key="layoutItem.key">
                <el-card :body-style="{ padding: '10px'}">
                  <img :src="layoutItem.imageUrl"
                       class="image"
                       style="width: 100%;">
                  <div class="bottom clearfix">
                    <span class="layoutTitle">{{layoutItem.title}}</span>
                    <el-button class="button"
                               size="small"
                               :label="layoutItem.label"
                               @click="addWidget(layoutItem.key)"
                               type="primary">{{$t('add')}}</el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane :label="$t('custom.dashboard.layoutCustomized')">
            <el-row>
              <el-col :span="6"
                      class="layout-item"
                      v-for="layoutItem in customizedLayoutItems"
                      :key="layoutItem.key">
                <el-card :body-style="{ padding: '10px'}">
                  <img :src="layoutItem.imageUrl"
                       class="image"
                       style="width: 100%;">
                  <div class="bottom clearfix">
                    <span style="font-size: 12px;">{{layoutItem.title}}</span>
                    <el-button class="button"
                               size="small"
                               :label="layoutItem.label"
                               @click="addWidget(layoutItem.key)"
                               type="primary">{{$t('add')}}</el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-container>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialog = false"
                   type="danger">{{ $t('custom.dashboard.close') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import Vue from 'vue'
import VueGridLayout from 'vue-grid-layout'

import pvtable from '@/components/gadget/pvtable/pvtable-gadget.vue'
import grid from '@/components/gadget/grid/grid-gadget.vue'
import gridgadget from '@/components/gadget/grid-gadget/grid-gadget.vue'
import chartgadget from '@/components/gadget/chart-line/line-gadget.vue'
import barchartgadget from '@/components/gadget/chart-bar/bar-gadget.vue'
import piechartgadget from '@/components/gadget/chart-pie/pie-gadget.vue'
import listmenu from '@/components/gadget/list-menu/list-menu-gadget.vue'
import dateRangeSlicer from '@/components/gadget/dateRange-slicer/daterange-gadget.vue'
import dateSlicer from '@/components/gadget/date-slicer/date-slicer-gadget.vue'
import runReport from '@/components/gadget/runreport-action/runreport-gadget.vue'
import kpigadget from '@/components/gadget/kpi/kpi-gadget.vue'
import circulargauge from '@/components/gadget/circular-gauge/circular-gadget.vue'
import cardicon from '@/components/gadget/card-icon/card-icon-gadget.vue'
import cardlinegadget from '@/components/gadget/card-line/card-line-gadget.vue'
import autorefreshgadget from '@/components/gadget/auto-refresh/auto-refresh-gadget.vue'
import dropdownlistgadget from '@/components/gadget/dropdown-list-slicer/dropdown-list-gadget.vue'
import treegridgadget from '@/components/gadget/tree-grid-gadget/tree-grid-gadget.vue'
import menulistgadget from '@/components/gadget/customized/menuList/menuList-gadget.vue'
import linkbuttongadget from '@/components/gadget/link-button/link-button-gadget.vue'
import checkboxgadget from '@/components/gadget/checkbox-slicer/checkbox-gadget.vue'
import multiselectgadget from '@/components/gadget/multi-select-slicer/multi-select-gadget'
import cardnumbergadget from '@/components/gadget/card-number/card-number-gadget.vue'
import placeholdergadget from '@/components/gadget/place-holder/place-holder-gadget.vue'
import { getUUID } from '@/utils'
// Customized
import bottriggerreportgadget from '@/components/gadget/customized/bot-trigger/bot-trigger-gadget.vue'
import stepgadget from '@/components/gadget/step-line/step-line-gadget.vue'
import newstepgadget from '@/components/gadget/new-step-line/new-step-line-gadget.vue'
import customizedmultiselectgadget from '@/components/gadget/customized/multi-select-slicer/multi-select-gadget'
import getDrillThroughFields from '@/components/gadget/get-drill-through-fields/index'
import enterinputgadget from '@/components/gadget/enter-input-slicer/enter-input-gadget.vue'

export default {
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    grid,
    gridgadget,
    pvtable,
    chartgadget,
    barchartgadget,
    piechartgadget,
    listmenu,
    dateRangeSlicer,
    runReport,
    kpigadget,
    circulargauge,
    cardicon,
    cardlinegadget,
    dateSlicer,
    autorefreshgadget,
    dropdownlistgadget,
    treegridgadget,
    menulistgadget,
    linkbuttongadget,
    checkboxgadget,
    multiselectgadget,
    cardnumbergadget,
    placeholdergadget,
    // Customized
    bottriggerreportgadget,
    stepgadget,
    newstepgadget,

    customizedmultiselectgadget,
    getDrillThroughFields,
    enterinputgadget
  },
  provide () {
    return {
      gadgetMessageBus: this.gadgetMessageBus,
      slicer: this.slicer,
      filters: this.filters,
      gadgetInfos: () => this.gadgetInfos
    }
  },
  props: {
    actionPageId: {
      type: null,
      default: null
    }
  },
  data () {
    // let getPageid = () => { return this.actionPageId }
    return {
      // pageId: getPageid(),
      gadgetMessageBus: new Vue(),
      slicer: {},
      filters: [],
      gadgetInfos: [],
      showCloseIcon: true,
      contenttemplateVue: '',
      editMode: false,
      editText: 'Edit',
      dashbordDefaultSetting: {
        allowResizing: false,
        allowDragging: false,
        responsive: true
      },
      gadgets: [],
      dialog: false,
      selectedgadget: '',
      loading: false,
      layoutItems: [
        // {
        //   key: 'grid',
        //   title: this.$t('custom.dashboard.layoutItem.gridTitle'),
        //   label: this.$t('custom.dashboard.layoutItem.gridLabel'),
        //   imageUrl: 'https://oss.mspbots.ai/app/dashboard/20200708170303.png'
        // },
        {
          key: 'gridgadget',
          title: this.$t('custom.dashboard.layoutItem.gridgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.gridgadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200708170303.png'
        },
        {
          key: 'pvtable',
          title: this.$t('custom.dashboard.layoutItem.pvtablegadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.pvtableLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200708170310.png'
        },
        {
          key: 'chartgadget',
          title: this.$t('custom.dashboard.layoutItem.chartgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.chartgadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200708170256.png'
        },
        {
          key: 'barchartgadget',
          title: this.$t('custom.dashboard.layoutItem.barchartgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.barchartgadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200709143707.png'
        },
        {
          key: 'piechartgadget',
          title: this.$t('custom.dashboard.layoutItem.piechartgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.piechartgadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200709143659.png'
        },
        // {
        //   key: 'listmenu',
        //   title: this.$t('custom.dashboard.layoutItem.listmenuTitle'),
        //   label: this.$t('custom.dashboard.layoutItem.listmenuLabel'),
        //   imageUrl: 'https://oss.mspbots.ai/app/dashboard/20200708170247.png'
        // },
        {
          key: 'dateRangeSlicer',
          title: this.$t('custom.dashboard.layoutItem.dateRangeSlicerTitle'),
          label: this.$t('custom.dashboard.layoutItem.daterangeSlicerLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/daterange.png'
        },
        {
          key: 'runReport',
          title: this.$t('custom.dashboard.layoutItem.runReportTitle'),
          label: this.$t('custom.dashboard.layoutItem.runreportLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/button.png'
        },
        {
          key: 'kpigadget',
          title: this.$t('custom.dashboard.layoutItem.kpigadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.kpiLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200713111020.png'
        },
        {
          key: 'circulargauge',
          title: this.$t('custom.dashboard.layoutItem.circulargaugeTitle'),
          label: this.$t('custom.dashboard.layoutItem.circularguagegadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/20200713110301.png'
        },
        {
          key: 'cardicon',
          title: this.$t('custom.dashboard.layoutItem.cardiconTitle'),
          label: this.$t('custom.dashboard.layoutItem.cardicongadgetLabel'),
          imageUrl: this.$ossLink + '/app/dashboard/icon-card.png'
        },
        {
          key: 'cardlinegadget',
          title: this.$t('custom.dashboard.layoutItem.cardlinegadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.cardlinegadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/cardline.png'
        },
        {
          key: 'dateSlicer',
          title: this.$t('custom.dashboard.layoutItem.dateSlicerTitle'),
          label: this.$t('custom.dashboard.layoutItem.dateslicergadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/monthdatepicker.png'
        },
        {
          key: 'autorefreshgadget',
          title: this.$t('custom.dashboard.layoutItem.autorefreshgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.autorefreshgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/auto-refresh.png'
        },
        {
          key: 'dropdownlistgadget',
          title: this.$t('custom.dashboard.layoutItem.dropdownlistgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.dropdownlistgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/auto-refresh.png'
        },
        {
          key: 'treegridgadget',
          title: this.$t('custom.dashboard.layoutItem.treegridgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.treegridgadgetLable'),
          imageUrl: this.$ossLink + '/app/mspbots_theme_icon/tree_grid.png'
        },
        {
          key: 'menulistgadget',
          title: this.$t('custom.dashboard.layoutItem.menulistgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.menulistgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/auto-refresh.png'
        },
        {
          key: 'linkbuttongadget',
          title: this.$t('custom.dashboard.layoutItem.linkbuttongadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.linkbuttongadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/link-button.png'
        },
        {
          key: 'checkboxgadget',
          title: this.$t('custom.dashboard.layoutItem.checkboxgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.checkboxgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'multiselectgadget',
          title: this.$t('custom.dashboard.layoutItem.multiselectgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.multiselectgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'cardnumbergadget',
          title: this.$t('custom.dashboard.layoutItem.cardnumbergadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.cardnumbergadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'placeholdergadget',
          title: this.$t('custom.dashboard.layoutItem.placeholdergadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.placeholdergadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'enterinputgadget',
          title: this.$t('custom.dashboard.layoutItem.enterinputgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.enterinputgadgetLable'),
          imageUrl: this.$ossLink + '/app/mspbots_theme_icon/slicer_input.png'
        }
      ],
      customizedLayoutItems: [
        {
          key: 'bottriggerreportgadget',
          title: this.$t('custom.dashboard.layoutItem.bottriggerreportgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.bottriggerreportgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'stepgadget',
          title: this.$t('custom.dashboard.layoutItem.newstepgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.newgetstartprogressLable'),
          imageUrl: this.$ossLink + '/app/dashboard/getstartedprogress.png'
        },
        {
          key: 'newstepgadget',
          title: this.$t('custom.dashboard.layoutItem.newstepgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.newgetstartprogressLable'),
          imageUrl: this.$ossLink + '/app/dashboard/getstartedprogress.png'
        },
        {
          key: 'customizedmultiselectgadget',
          title: this.$t('custom.dashboard.layoutItem.customizedmultiselectgadgetTitle'),
          label: this.$t('custom.dashboard.layoutItem.customizedmultiselectgadgetLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        },
        {
          key: 'getDrillThroughFields',
          title: this.$t('custom.dashboard.layoutItem.getDrillThroughFieldsTitle'),
          label: this.$t('custom.dashboard.layoutItem.getDrillThroughFieldsLable'),
          imageUrl: this.$ossLink + '/app/dashboard/checkbox.png'
        }
      ],
      dashboardId: null
    }
  },
  computed: {
    pageId () {
      return this.actionPageId
    }
  },
  created () {
    this.getDashboardLayout()
  },
  beforeDestroy () {
    this.gadgetMessageBus.$off()
  },
  methods: {
    getSlicerInfo () {
      this.slicer = Object.assign({}, { ...this.slicer, ...this.$store.state.drillThrough.data })
    },
    getDashboardLayout () {
      let _self = this
      _self.loading = true
      _self.gadgetInfos = []
      const params = {
        businessId: _self.actionPageId
      }
      _self.$interface.reports.getDashboardLayout(params).then(({ data: res }) => {
        _self.loading = false
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
        if (res.data) {
          _self.dashboardId = res.data.id
          _self.gadgets = ((res.data.contentNew && res.data.contentNew.length) > 0 ? res.data.contentNew : JSON.parse(res.data.content)) || []
          _self._.forEach(_self.gadgets, function (value, key) {
            _self.gadgetInfos.push(
              {
                id: value.i,
                gadgetStatus: 'init',
                gadgetType: ''
              }
            )
          })
          _self.$store.commit('SET_GADGET_LAYOUT', _self.gadgets)
        }
      })
    },
    gadgetDragChanged (e) {
      this.dashbordDefaultSetting.allowDragging = e.state
    },
    gadgetRemoved (e) {
      var index = this.getGadgetIndex(e.id)
      this.gadgets.splice(index, 1)
      this.onSave()
    },
    getGadgetIndex (id) {
      for (var i = 0; i < this.gadgets.length; i++) {
        if (this.gadgets[i].i === id) {
          return i
        }
      }
    },
    onSave () {
      let dashboardlayout = JSON.stringify(this.gadgets)
      if (dashboardlayout) {
        const params = {
          tenantCode: this.$store.state.user.tenantCode,
          type: 1,
          businessId: this.actionPageId,
          content: dashboardlayout,
          contentNew: this.gadgets,
          id: this.dashboardId
        }
        this.$interface.reports.saveDashboardLayout(params).then(({ data: res }) => {
          this.gadgetMessageBus.$emit(this.pageId + 'closeLoading')
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            return this.$message.success(this.$t('custom.dashboard.layoutSavedMessage') + res.msg)
          }
        })
      }
    },
    toggleClick () {
      this.editMode = !this.editMode
      if (this.editMode) {
        this.dashbordDefaultSetting.allowResizing = true
        this.editText = 'Save'
      } else {
        this.onSave()
        this.dashbordDefaultSetting.allowResizing = false
        this.editText = 'Edit'
      }
    },
    selectedgadgetPop () {
      this.dialog = true
    },
    addWidget (key) {
      this.dialog = false
      var item = { 'x': 0, 'y': 0, 'w': 5, 'h': 5, 'i': getUUID(), com: key }
      this.gadgets.push(item)
    },
    resizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.gadgets[index].h = newH
      this.gadgets[index].w = newW

      this.$refs.gadgets[index].resized(i, newH, newW, newHPx, newWPx)
    },
    containerResizedEvent: function (i, newH, newW, newHPx, newWPx) {
      var index = this.getGadgetIndex(i)
      this.gadgets[index].h = newH
      this.gadgets[index].w = newW

      this.$refs.gadgets[index].containerResizedEvent(i, newH, newW, newHPx, newWPx)
    },
    mouseEnterModule (index) {
      if (this.editMode) {
        this.$set(this.gadgets[index], 'showSetting', 'show')
      }
    },
    mouseLeaveModule (index) {
      if (this.editMode) {
        this.$delete(this.gadgets[index], 'showSetting')
      }
    },
    moveComponent (status) {
      if (this.editMode) {
        this.gadgetDragChanged({ state: status })
      }
    },
    editComponent (componentId) {
      try {
        let index = this.getGadgetIndex(componentId)
        this.$refs.gadgets[index].showQueryModel()
      } catch (error) { }
    },
    closeComponent (componentId) {
      this.gadgetRemoved({ id: componentId })
    }
  }
}
</script>
<style  >
.layoutTitle {
  font-size: 12px;
  word-break: keep-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.layoutTitle:hover {
  overflow: visible;
}
.vue-grid-item.vue-grid-placeholder {
  background: #f2f8ff;
  border: 1px solid #38f;
  opacity: 1;
}

.layoutJSON {
  background: #ddd;
  border: 1px solid black;
  margin-top: 10px;
  padding: 10px;
}

.eventsJSON {
  background: #ddd;
  border: 1px solid black;
  margin-top: 10px;
  padding: 10px;
  height: 100px;
  overflow-y: scroll;
}

.columns {
  -moz-columns: 120px;
  -webkit-columns: 120px;
  columns: 120px;
}

.vue-resizable-handle {
  z-index: 5000;
  position: absolute;
  width: 20px;
  height: 20px;
  bottom: 0;
  right: 0;
  background: url("");
  background-position: bottom right;
  padding: 0 3px 3px 0;
  background-repeat: no-repeat;
  background-origin: content-box;
  box-sizing: border-box;
  cursor: se-resize;
}

.editmode:not(.vue-grid-placeholder) {
  border: 1px solid #38f;
  opacity: 0.5;
}

.vue-grid-item.resizing {
  opacity: 0.9;
}

.vue-grid-item .no-drag {
  height: 100%;
  width: 100%;
}

.vue-grid-item .minMax {
  font-size: 12px;
}

.vue-grid-item .add {
  cursor: pointer;
}

.vue-draggable-handle {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 0;
  left: 0;
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><circle cx='5' cy='5' r='5' fill='#999999'/></svg>")
    no-repeat;
  background-position: bottom right;
  padding: 0 8px 8px 0;
  background-repeat: no-repeat;
  background-origin: content-box;
  box-sizing: border-box;
  cursor: pointer;
}

.layout-item {
  text-align: center;
  margin-bottom: 15px;
  padding: 0 5px;
}

.layout-item .bottom {
  position: relative;
  margin-top: 15px;
}

.layout-item .bottom span {
  display: block;
  float: left;
  width: 50%;
  margin-top: 12px;
  text-align: left;
}

.layout-item .bottom button {
  padding-top: 0;
}
</style>
